<template>
  <section class="todoapp">
	<header class="header">
		<h1>todos</h1>
		<input class="new-todo" @keyup.enter="addTodo" v-model.trim="todoList" placeholder="What needs to be done?" autofocus>
	</header>
    
	<section class="main">
		<input id="toggle-all" class="toggle-all" type="checkbox" v-model="ischeckAll">
		<label for="toggle-all">Mark all as complete</label>
		<ul class="todo-list">
			<li :class="{completed:item.flag}" v-for="item in list" :key="item.id" >
				<div class="view">
					<input class="toggle" type="checkbox" v-model="item.flag">
					<label>{{item.name}}</label>
					<button class="destroy" @click="delToda(item.id)"></button>
				</div>
				<input class="edit" value="Create a TodoMVC template">
			</li>
			
		</ul>
	</section>
    
	<footer class="footer">
		<span class="todo-count"><strong>{{todoLength}}</strong> item left</span>
		<ul class="filters">
			<li>
				<a class="selected" href="#/">All</a>
			</li>
			<li>
				<a href="#/active">Active</a>
			</li>
			<li>
				<a href="#/completed">Completed</a>
			</li>
		</ul>
		<button class="clear-completed">Clear completed</button>
	</footer>
</section>
</template>

<script>
import {computed, reactive, toRefs, watch} from 'vue'
export default {
    setup () {
        // 数据定义
      const state = reactive({
          list: JSON.parse(localStorage.getItem('todouList'))||[
              {id:1, name:'打豆豆', flag: true},
              {id:2, name:'睡觉', flag: false},
              {id:3, name:'干饭', flag: false}
          ],
          todoList:''
      })

    //   删除
    const delToda = (id) => {
      state.list = state.list.filter(item=> item.id !== id)
    }

    // 添加
    const addTodo = () => {
        if(!state.todoList) return alert('请输入内容')
        const obj = {
            id:state.list.length+1,
            name:state.todoList,
            flag:false
        }
        state.list = [obj,...state.list]
    }

    // 底部长度
    const todoLength = computed(()=>{
        return state.list.filter(item=> item.flag === false).length
    })


    // 全选反选功能
    const ischeckAll = computed({
        get:()=>{
            return state.list.every(item=> item.flag === true)
        },
        set:(val)=>{
            state.list.forEach(item=>item.flag = val)
        }
    })

    // watch监听数据并数据持久化
    watch(()=>state.list, ()=>{
        localStorage.setItem('todouList',JSON.stringify(state.list))
    },{deep:true})
     return {...toRefs(state), delToda,addTodo,todoLength, ischeckAll}
    }
}
</script>

<style>

</style>